package com.ocom.payconfig.controller;


import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.payconfig.EntityDishesFoodstuff;
import com.ocom.common.entity.payconfig.EntityFoodstuffClass;
import com.ocom.common.entity.payconfig.EntityFoodstuffInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.food.*;
import com.ocom.common.resp.Result;
import com.ocom.common.response.payconfig.DishesStuffListPartVo;
import com.ocom.common.response.payconfig.DishesStuffListVo;
import com.ocom.common.response.payconfig.OrderSummaryVo;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.payconfig.MealDateSummaryVo;
import com.ocom.payconfig.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class FoodController {

    @Autowired
    private FoodstuffClassService foodstuffClassService;
    
    @Autowired
    private FoodstuffInfoService foodstuffInfoService;

    @Autowired
    private DishesFoodstuffService dishesFoodstuffService;

    @Autowired
    private DishesInfoService dishesInfoService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;


    //11.8.1食材分类列表（foodClassList）
    @PostMapping(PayConfigUrl.Url_foodClassList)
    public Result foodClassList(@RequestBody ComMerchRequest request) {
        return ResultUtil.success(foodstuffClassService.getList(request.getComId(), request.getMerchId()));
    }

    //11.8.2删除菜品分类（removeFoodClass）
    @PostMapping(PayConfigUrl.Url_removeFoodClass)
    public Result removeFoodClass(@RequestBody FoodClassIdRequest request) {
        Integer count = foodstuffClassService.getChild(request.getComId(), request);
        if (count > 0) {
            return ResultUtil.error(ResultEnum.Err_3089);
        }

        Integer count1 = foodstuffInfoService.getOnline(request.getComId(), request.getMerchId(), request.getFoodClassId());
        if (count1 > 0) {
            return ResultUtil.error(ResultEnum.Err_3090);
        }
        foodstuffClassService.removeByClassId(request.getComId(), request);
        return ResultUtil.success();
    }

    //11.8.3添加菜品分类（newFoodClass）
    @PostMapping(PayConfigUrl.Url_newFoodClass)
    public Result newFoodClass(@RequestBody NewFoodClassRequest request) {
        if (request.getParentId() > 0) {
            Integer count = foodstuffClassService.getParent(request.getComId(), request.getMerchId(), request.getParentId());
            if (count > 0) {
                return ResultUtil.error(ResultEnum.Err_3091);
            }
        }

        Integer count1 = foodstuffClassService.getSameName(request.getComId(), request.getMerchId(), request.getFoodClassName(), false, null);
        if (count1 > 0) {
            return ResultUtil.error(ResultEnum.Err_3092);
        }

        foodstuffClassService.saveOne(request.getComId(), request);

        return ResultUtil.success();
    }

    //11.8.4修改菜品分类（updateFoodClass）
    @PostMapping(PayConfigUrl.Url_updateFoodClass)
    public Result updateFoodClass(@RequestBody NewFoodClassRequest request) {
        Integer count1 = foodstuffClassService.getSameName(request.getComId(), request.getMerchId(), request.getFoodClassName(), true, request.getFoodClassId());
        if (count1 > 0) {
            return ResultUtil.error(ResultEnum.Err_3092);
        }
        foodstuffClassService.updateOne(request.getComId(), request);
        return ResultUtil.success();
    }

    //11.8.5获取下级菜品分类列表（getSubFoodClassList）
    @PostMapping(PayConfigUrl.Url_getSubFoodClassList)
    public Result getSubFoodClassList(@RequestBody FoodClassIdRequest request) {
        List<EntityFoodstuffClass> list = foodstuffClassService.getAllChild(request.getComId(), request);
        if (list.size() == 0) {
            return ResultUtil.success("");
        }
        List<Integer> classIds = list.stream().map(EntityFoodstuffClass::getFoodClassId).collect(Collectors.toList());
        return ResultUtil.success(Joiner.on(",").join(classIds));
    }


    //11.9.1食材列表（getFoodstuffList）
    @PostMapping(PayConfigUrl.Url_getFoodstuffList)
    public Result getFoodstuffList(@RequestBody GetFoodstuffListRequest request) {
        PageInfo<EntityFoodstuffInfo> pageInfo = foodstuffInfoService.getList(request.getComId(), request);
        if (pageInfo.getSize() > 0) {
            List<EntityFoodstuffClass> list = foodstuffClassService.getList(request.getComId(), null);
            //list转map
            Map<Integer, String> stringMap = list.stream().collect(Collectors.toMap(e -> e.getFoodClassId(),
                    e -> e.getFoodClassName(),
                    (e1, e2) -> e1));
            List<EntityFoodstuffInfo> entityFoodstuffInfoList = pageInfo.getList();
            for (EntityFoodstuffInfo entityFoodstuffInfo : entityFoodstuffInfoList) {
                if (stringMap.containsKey(entityFoodstuffInfo.getFoodClassId())) {
                    entityFoodstuffInfo.setFoodClassName(stringMap.get(entityFoodstuffInfo.getFoodClassId()));
                }
            }
            pageInfo.setList(entityFoodstuffInfoList);
        }
        return ResultUtil.success(pageInfo);
    }

    //11.9.2删除食材（removeFoodstuff）
    @PostMapping(PayConfigUrl.Url_removeFoodstuff)
    public Result removeFoodstuff(@RequestBody FoodstuffIdRequest request) {
        Integer count = dishesFoodstuffService.getCountByFoodstuffId(request.getComId(), request);
        if (count > 0) {
            return ResultUtil.error(ResultEnum.Err_3093);
        }
        dishesFoodstuffService.deleteByFoodstuffId(request.getComId(), request);
        return ResultUtil.success();
    }

    //11.9.3增加食材（newFoodstuff）
    @PostMapping(PayConfigUrl.Url_newFoodstuff)
    public Result newFoodstuff(@RequestBody EntityFoodstuffInfo foodstuffInfo) {
        if (foodstuffInfo.getFoodClassId() <= 0) {
            return ResultUtil.error(ResultEnum.Err_3094);
        }
        Integer count1 = foodstuffClassService.getParent(foodstuffInfo.getComId(), foodstuffInfo.getMerchId(), foodstuffInfo.getFoodClassId());
        if (count1 < 0) {
            return ResultUtil.error(ResultEnum.Err_3095);
        }
        Integer count2 = foodstuffInfoService.getSameNameCode(foodstuffInfo.getComId(),
                foodstuffInfo.getMerchId(),
                foodstuffInfo.getFoodstuffCode(),
                foodstuffInfo.getFoodstuffName(),
                false,
                null
        );
        if (count2 > 0) {
            return ResultUtil.error(ResultEnum.Err_3096);
        }
        foodstuffInfo.setSort(foodstuffInfoService.getMaxSort(foodstuffInfo.getComId(), foodstuffInfo));
        foodstuffInfoService.saveOne(foodstuffInfo.getComId(), foodstuffInfo);

        return ResultUtil.success();
    }

    //11.9.4修改食材（updateFoodstuff）
    @PostMapping(PayConfigUrl.Url_updateFoodstuff)
    public Result updateFoodstuff(@RequestBody EntityFoodstuffInfo foodstuffInfo) {
        if (foodstuffInfo.getFoodClassId() <= 0) {
            return ResultUtil.error(ResultEnum.Err_3094);
        }
        Integer count1 = foodstuffClassService.getParent(foodstuffInfo.getComId(), foodstuffInfo.getMerchId(), foodstuffInfo.getFoodClassId());
        if (count1 < 0) {
            return ResultUtil.error(ResultEnum.Err_3095);
        }
        Integer count2 = foodstuffInfoService.getSameNameCode(foodstuffInfo.getComId(),
                foodstuffInfo.getMerchId(),
                foodstuffInfo.getFoodstuffCode(),
                foodstuffInfo.getFoodstuffName(),
                true,
                foodstuffInfo.getFoodstuffId()
        );
        if (count2 > 0) {
            return ResultUtil.error(ResultEnum.Err_3096);
        }
        foodstuffInfoService.updateOne(foodstuffInfo.getComId(), foodstuffInfo);
        return ResultUtil.success();
    }

    //11.9.5菜品食材含量列表（getDishesStuffList）
    @PostMapping(PayConfigUrl.Url_getDishesStuffList)
    public Result getDishesStuffList(@RequestBody GetDishesStuffListRequest request) {
        List<EntityDishesFoodstuff> list = dishesFoodstuffService.getList(request.getComId(), request.getMerchId(), request.getDishesId());
        if (list.size() == 0) {
            return ResultUtil.success(new ArrayList<>());
        }
        List<DishesStuffListVo> dishesStuffListVo = new ArrayList<>();
        for (EntityDishesFoodstuff dishesFoodstuff : list) {
            List<Integer> classIds =new ArrayList<>();
            if(dishesStuffListVo.size()>0){
                classIds = dishesStuffListVo.stream().map(DishesStuffListVo::getFoodstuffId).collect(Collectors.toList());
            }
            if (classIds.contains(dishesFoodstuff.getFoodstuffId())) {
                for (int i = 0; i < dishesStuffListVo.size(); i++) {
                    DishesStuffListVo dishesStuffListVo1 = dishesStuffListVo.get(i);
                    if (dishesFoodstuff.getFoodstuffId().equals(dishesStuffListVo1.getFoodstuffId())) {
                        DishesStuffListPartVo dishesStuffListPartVo = new DishesStuffListPartVo();
                        dishesStuffListPartVo.setPriceMode(dishesFoodstuff.getPriceMode());
                        dishesStuffListPartVo.setWeight(dishesFoodstuff.getWeight());
                        dishesStuffListVo1.getPart().add(dishesStuffListPartVo);
                        dishesStuffListVo.set(i, dishesStuffListVo1);
                    }
                }
            } else {
                DishesStuffListVo dishesStuffListVo1 = new DishesStuffListVo();
                dishesStuffListVo1.setFoodstuffId(dishesFoodstuff.getFoodstuffId());
                dishesStuffListVo1.setFoodClassName(dishesFoodstuff.getFoodClassName());
                dishesStuffListVo1.setFoodstuffName(dishesFoodstuff.getFoodstuffName());

                DishesStuffListPartVo dishesStuffListPartVo = new DishesStuffListPartVo();
                dishesStuffListPartVo.setPriceMode(dishesFoodstuff.getPriceMode());
                dishesStuffListPartVo.setWeight(dishesFoodstuff.getWeight());
                dishesStuffListVo1.getPart().add(dishesStuffListPartVo);
                dishesStuffListVo.add(dishesStuffListVo1);
            }
        }
        return ResultUtil.success(dishesStuffListVo);
    }

    //11.9.6设置食材含量（setDishesStuff）
    @PostMapping(PayConfigUrl.Url_setDishesStuff)
    public Result setDishesStuff(@RequestBody EntityDishesFoodstuff entityDishesFoodstuff) {
        dishesFoodstuffService.updateOne(entityDishesFoodstuff.getComId(), entityDishesFoodstuff);
        return ResultUtil.success();
    }

    //11.9.7移除食材含量（removeDishesStuff）
    @PostMapping(PayConfigUrl.Url_removeDishesStuff)
    public Result removeDishesStuff(@RequestBody EntityDishesFoodstuff entityDishesFoodstuff) {
        dishesFoodstuffService.deleteOne(entityDishesFoodstuff.getComId(), entityDishesFoodstuff);
        return ResultUtil.success();
    }


    //11.4.21订餐统计（orderSummary）
    @PostMapping(PayConfigUrl.Url_orderSummary)
    public Result orderSummary(@RequestBody OrderSummaryRequest request) {

        OrderSummaryVo orderSummaryVo = new OrderSummaryVo();

        List<MealDateSummaryVo> mealDateSummaryVos = xfGoodsListProcessService.mealDateSummary(request.getComId(), request.getPointId(), request.getMealNos(), request.getBeginDate(), request.getEndDate());

        List<OrderSummaryVo.MealList> mealList = new ArrayList<>();

        if (mealDateSummaryVos.size() > 0) {

            List<Integer> dishesIds = new ArrayList();
            for (MealDateSummaryVo mealDateSummaryVo : mealDateSummaryVos) {
                Boolean exist = false;
                int jk = 0;
                for (int i = 0; i < mealList.size(); i++) {
                    OrderSummaryVo.MealList mealList1 = mealList.get(i);
                    if (mealList1.getMealDate().equals(mealDateSummaryVo.getMealDate())
                            && mealList1.getMealNo().equals(mealDateSummaryVo.getMealNo())
                    ) {
                        exist = true;
                        jk = i;
                        break;
                    }
                }
                OrderSummaryVo.DishesData dishesData = new OrderSummaryVo.DishesData();
                dishesData.setDishesId(mealDateSummaryVo.getDishesId());
                dishesData.setOrderNumber(mealDateSummaryVo.getOrderNumber());
                dishesData.setPriceMode(20);

                if (!dishesIds.contains(mealDateSummaryVo.getDishesId())) {
                    dishesIds.add(mealDateSummaryVo.getDishesId());
                }

                if (exist) {
                    mealList.get(jk).getDishesData().add(dishesData);
                } else {
                    OrderSummaryVo.MealList mealDateSummaryVo1 = new OrderSummaryVo.MealList();
                    mealDateSummaryVo1.setMealDate(mealDateSummaryVo.getMealDate());
                    mealDateSummaryVo1.setMealNo(mealDateSummaryVo.getMealNo());
                    mealDateSummaryVo1.setMealName(mealDateSummaryVo.getMealName());
                    mealDateSummaryVo1.getDishesData().add(dishesData);
                    mealList.add(mealDateSummaryVo1);
                }
            }


            //计算使用的食材
            List<EntityDishesFoodstuff> foodstuffList = dishesFoodstuffService.getList(request.getComId(), dishesIds);


            for (int i = 0; i < mealList.size(); i++) {
                OrderSummaryVo.MealList mealList1 = mealList.get(i);
                for (OrderSummaryVo.DishesData dishesData : mealList1.getDishesData()) {
                    for (EntityDishesFoodstuff foodstuff : foodstuffList) {
                        List<Integer> foodList = mealList1.getFoodData().stream().map(OrderSummaryVo.FoodData::getFoodstuffId).collect(Collectors.toList());
                        //菜品中包含食材计算
                        if (dishesData.getDishesId().equals(foodstuff.getDishesId())) {
                            if (foodList.contains(foodstuff.getFoodstuffId())) {
                                for (int j = 0; j < mealList1.getFoodData().size(); j++) {
                                    OrderSummaryVo.FoodData foodData = mealList1.getFoodData().get(j);
                                    foodData.setRequiredNumber(foodData.getRequiredNumber() + dishesData.getOrderNumber() * foodstuff.getWeight());
                                    mealList1.getFoodData().set(j, foodData);
                                }
                            } else {
                                OrderSummaryVo.FoodData foodData = new OrderSummaryVo.FoodData();
                                foodData.setFoodstuffId(foodstuff.getFoodstuffId());
                                foodData.setRequiredNumber(dishesData.getOrderNumber() * foodstuff.getWeight());
                                mealList1.getFoodData().add(foodData);
                            }
                        } else {
                            continue;
                        }
                    }
                }
                mealList.set(i,mealList1);
            }

        }


        orderSummaryVo.setMealList(mealList);


        orderSummaryVo.setDishesList(dishesInfoService.getDishesList(request.getComId(), new ArrayList<>()));
        orderSummaryVo.setFoodstuffList(foodstuffInfoService.getFoodstuffList(request.getComId(), new ArrayList<>()));


        return ResultUtil.success(orderSummaryVo);
    }


}
